/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.google.code.twiddling.core.resource;

import java.util.HashMap;

/**
 * The ResourceRepository keeps a repository of resources for
 * Contexts. When a context is 'mounted', it optionally can register
 * some ResourceResolvers, usually contributed to the whole shell, 
 * available for any other contexts. 
 * 
 * A Context provides a set of commands and environments that can carry out
 * some specific tasks.
 * 
 * A Context can have resources and their resolvers for their command to execute against.
 * 
 * for example:
 * 
 * db context has sql as their commands,
 * 
 * Time to define some built in commands
 * 
 * mount - mount a new context under current or an absolute context;
 * e.g. mount as5 
 * cd - go to a context by name or path.
 * ls - list cuttent contexts under current.
 * umount - remove a context.
 * 
 * 
 * @author howard
 *
 */
public class ResourceRepository {

	HashMap<String, ResourceResolver> resolvers = new HashMap<String, ResourceResolver>();
	HashMap<String, Resource> resources = new HashMap<String, Resource>();
	
	public void registerResolver(ResourceResolver resolver) {
		String key = getKey(resolver);
		resolvers.put(key, resolver);
	}
	
	public Resource getResource(String url) throws ResourceNotResolvedException, InvalidUrlException {
		Resource res = resources.get(url);
		if (res == null) {
			String key = getResourceKey(url);
			ResourceResolver resolver = resolvers.get(key);
			if (resolver == null) {
				throw new ResourceNotResolvedException();
			}
			res = resolver.resolve();
			resources.put(url, res);
		}
		return res;
	}
	
	/*
	 * file:local:///home/howard
	 * key = file:local
	 */
	private String getResourceKey(String url) throws InvalidUrlException {
		String[] fields = url.split(":");
		if (fields.length < 2) {
			throw new InvalidUrlException();
		}
		return fields[0] + ":" + fields[1];
	}

	private String getKey(ResourceResolver resolver) {
		StringBuffer keyBuffer = new StringBuffer();
		keyBuffer.append(resolver.getType());
		keyBuffer.append(":");
		keyBuffer.append(resolver.getProtocol());
		return keyBuffer.toString();
	}
	
}
